package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = "02.微博模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    //自动装配RedisTemplate[从IOC容器中获取Bean对象]
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @ApiOperation("发布微博功能")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        log.debug("weiboDTO = " + weiboDTO);
        //接受客户端传递的数据
        UserVO userVO = (UserVO) session.getAttribute("user");
        //登录状态正确，发布成功
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }
    @ApiOperation("查询首页微博功能")
    @GetMapping("selectIndex")
    public JsonResult weiboVOList() throws JsonProcessingException {
         /*
            Redis中key-value: {"weibo_index": 具体首页数据}
            1.确认缓存[Redis]中是否存在首页数据;
            2.缓存中存在,直接返回;
            3.缓存中不存在,查询数据库,将数据保存到缓存[redis]中,返回;
         */
        // opsForValue: 创建操作字符串类型的对象ops
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable weiboIndex = ops.get("weibo_index");
        if (weiboIndex == null){
            //缓存中不存在,查询数据库,将数据保存到缓存[redis]中,返回;
            List<WeiboVO> weiboIndexVOS = weiboMapper.selectIndex();
            //Jackson: 序列化和反序列化的库;
            //将Java对象[List集合weiboIndexVOS]序列化为JSON格式之后,再存入Redis数据;
            ObjectMapper objectMapper = new ObjectMapper();
            String indexJson = objectMapper.writeValueAsString(weiboIndexVOS);
            //存入Redis
            ops.set("weibo_index", indexJson);
            System.out.println("首页数据来自MYSQL数据库");
            return JsonResult.ok(weiboIndexVOS);
        }
        // 缓存中存在,直接返回;
        System.out.println("首页数据来自Redis缓存");
        // 反序列化：将JSON格式的数据转换为Java对象[List集合]
        ObjectMapper objectMapper = new ObjectMapper();
        List<WeiboVO> indexVOList = objectMapper.readValue(weiboIndex.toString(), List.class);

        return JsonResult.ok(indexVOList);
    }
    @ApiOperation("根据微博id查询微博详情")
    @GetMapping("selectById")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "微博编号",required = true,
            dataType = "int",example = "200"),
            @ApiImplicitParam(name = "username",value = "用户名",required = true,
            dataType = "string")
    })
    public JsonResult selectById(@Range(min = 100,max = 500,
            message = "微博id范围在5-15之间")@RequestParam int id,String username) {
        //手动抛出异常
        if (id < 0){
            throw new IllegalArgumentException("微博id不能小于0");
        }
        log.debug("id = " + id);
        return JsonResult.ok(weiboMapper.selectById(id));
    }
}
